package com.rao.gmall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rao.gmall.common.constant.RedisConst;
import com.rao.gmall.common.util.IpUtil;
import com.rao.gmall.common.util.MD5;
import com.rao.gmall.model.user.UserAddress;
import com.rao.gmall.model.user.UserInfo;
import com.rao.gmall.user.mapper.UserAddressMapper;
import com.rao.gmall.user.mapper.UserInfoMapper;
import com.rao.gmall.user.service.UserService;
import org.bouncycastle.util.IPAddress;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author nzmxfan
 * @create 2021-08-16-20:18
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    UserAddressMapper userAddressMapper;

    /**
     * 用户登录认证
     * @param info
     * @return
     */
    @Override
    public UserInfo login(UserInfo info) {

        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", info.getLoginName());
        String passwd = info.getPasswd();
        String encrypt = MD5.encrypt(passwd);
        queryWrapper.eq("passwd", encrypt);

        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        return userInfo;
    }

    /**
     * 1.给前端返回 json 数据
     *  {
     *      code:xxx,
     *      message:"",
     *      data:{
     *          token:"登陆成功的令牌",
     *          nickName:"昵称"
     *      }
     *  }
     *
     * 2.用户登录成功，向 redis 中添加用户信息
     *  user:info：你的 token（设置过期时间）
     *  存的值：{"userId":1, "ipAddr": "192.111.111.111"}
     *
     *  3.下次前端任何请求，自己带上 token 的 cookie
     * @param userInfo
     * @param request
     * @return
     */
    @Override
    public Map<String, Object> handleLoginSuccess(UserInfo userInfo, HttpServletRequest request) {

        Map<String, Object> map = new HashMap<>();
        // 1.用户登录成功，生成 token
        String token = UUID.randomUUID().toString().replace("-","");

        // 数据写入 map 中
        map.put("token", token);
        map.put("nickName", userInfo.getNickName());

        // 2. 将用户登录的信息存到 redis
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        // 准备向 redis 中保存用户信息
        Map<String, Object> loginUser = new HashMap<>();
        loginUser.put("userId", userInfo.getId());
        // 后续权限验证，通过 userId ipAddr 鉴权
        // 工具类获取用户 ip
        String ipAddress = IpUtil.getIpAddress(request);
        loginUser.put("ipAddr", ipAddress);
        String loginUserInfo = null;
        try {
            loginUserInfo = new ObjectMapper().writeValueAsString(loginUser);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        // 将用户信息写入 redis 中
        operations.set(RedisConst.USER_LOGIN_KEY_PREFIX + token, loginUserInfo, RedisConst.USERKEY_TIMEOUT, TimeUnit.SECONDS);

        return map;
    }

    @Override
    public void logout(String token) {

        String string = RedisConst.USER_LOGIN_KEY_PREFIX + token;
        // 将 key 从 redis 中删除
        redisTemplate.delete(string);
    }

    @Override
    public List<UserAddress> getUserAddresses(String userId) {

        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", Long.parseLong(userId));
        return userAddressMapper.selectList(queryWrapper);
    }
}
